package com.woniuxy.microfundservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.woniuxy.bean.ResultBean;
import com.woniuxy.microfundservice.bean.AutomaticInvestment;
import com.woniuxy.microfundservice.dao.AutomaticInvestmentDao;
import com.woniuxy.microfundservice.dao.MemberDao;
import com.woniuxy.microfundservice.service.AutomaticInvestmentService;
import com.woniuxy.microfundservice.util.ErrorEntity;
import com.woniuxy.microfundservice.util.MD5;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Auther: yeyang  <br/>
 * Date: 2021/4/21 0021:上午 9:42  <br/>
 * Description:
 */
@Service
public class AutomaticInvestmentServiceImpl implements AutomaticInvestmentService {
    @Resource
    private AutomaticInvestmentDao atc;
    @Resource
    private MemberDao memberDao;


    @Override
    public ResultBean insertOne(AutomaticInvestment automaticInvestment) {

        //验证支付密码
        String oldPayPassword = memberDao.selectByAccount(automaticInvestment.getMemberName());
        //余额支付
        if (automaticInvestment.getPayType().contains(ErrorEntity.BALANCE) && oldPayPassword == null) {
            //支付密码为空：未实名
            return ResultBean.builder().code(607).msg(ErrorEntity.NO_REAL_NAME).build();
        }
        if (automaticInvestment.getPayType().contains(ErrorEntity.BALANCE) && ! oldPayPassword.equals(MD5.encrypt(automaticInvestment.getBankPassword()))) {
            //支付密码错误
            return ResultBean.builder().code(607).msg(ErrorEntity.WRONG_PASSWORD).build();
        }
        //银行卡支付
        if (automaticInvestment.getPayType().contains(ErrorEntity.BANKCARD)) {
            String bankPsw = memberDao.selectByid(automaticInvestment.getBankCardId());
            if(! automaticInvestment.getBankPassword().equals(bankPsw)){
                //支付密码错误
                return ResultBean.builder().code(607).msg(ErrorEntity.WRONG_PASSWORD).build();
            }
        }
        int res = atc.insertOne(automaticInvestment);

        if(res<1){
            return ResultBean.builder().code(800).msg("定投失败").build();
        }
        return ResultBean.builder().code(200).msg("定投成功").build();
    }

    @Override
    public ResultBean selectByName(String userName) {
        List<AutomaticInvestment> automaticInvestments = atc.selectByName(userName);
        if(automaticInvestments==null){
            return ResultBean.builder().code(800).msg("查找失败").build();
        }
        return ResultBean.builder().code(200).msg("查找成功").data(automaticInvestments).build();
    }

    @Override
    public ResultBean delOne(AutomaticInvestment automaticInvestment) {
        int res = atc.delOne(automaticInvestment);
        if(res<1){
            return ResultBean.builder().code(800).msg("删除失败").build();
        }
        return ResultBean.builder().code(200).msg("删除成功").build();
    }
}
